#include <iostream>
#include <unistd.h>
#include <cstdlib>
#include <cstdio>
#include <sys/types.h>
#include <sys/wait.h>
#include <string>
#include <string.h>

#define N 2
#define NUM 1024
using namespace std;

void writer(int wfd)
{
    string s = "hello, I am child";
    pid_t id = getpid();
    int number = 0;

    char buff[NUM];

    while (true)
    {
        buff[0] = 0; // 清空字符串，告诉使用者该buff是一个字符串
        // 构建字符串
        snprintf(buff, sizeof(buff), "%s-%d-%d", s.c_str(), id, number++);
        // 发送给父进程
        //  char ch='c';
        //  write(wfd,&ch,1);
        write(wfd, buff, strlen(buff));

        // cout<<number++<<endl;

        // if(number==5) break;

        sleep(1);
    }
}

void reader(int rfd)
{
    char buff[NUM];
    int cnt = 0;
    while (true)
    {
        // sleep(5);
        cnt++;
        buff[0] = 0;

        ssize_t n = read(rfd, buff, sizeof(buff));
        if (n > 0)
        {
            buff[n] = 0; // 0=='\0'
            cout << "father get massage[" << getpid() << "]#" << buff << endl;
        }

        else if(n==0)
        {
            cout<<"father file fail done"<<endl;
            break;
        }

       if (cnt >= 5)
        {
            cout << "father file read done" << endl;
            break;
        }
}
}

int main()
{
    int pipefd[N] = {0};
    int ret = pipe(pipefd);

    if (ret < 0)
        return 1;

    // cout<<"pipefd[0]: "<<pipefd[0]<<", pipefd[1]: "<<pipefd[1]<<endl;

    pid_t id = fork();
    if (id < 0)
        return 2;
    if (id == 0)
    {
        // child
        close(pipefd[0]);
        writer(pipefd[1]);

        close(pipefd[1]);
        exit(0);
    }
    
    // father
    close(pipefd[1]);
    reader(pipefd[0]);

    close(pipefd[0]);
    cout << "father close file done" << endl;

    sleep(5);

    int status = 0;

    pid_t rid = waitpid(id, &status, 0);
    if (rid < 0)
        return 3;

    cout << "wait sucess : " << rid << "exit code: " << ((status >> 8) & 0XFF) << "exit single: " << (status & 0X7F) << endl;

    sleep(5);

    return 0;
}